import { MessagePlugin } from 'tdesign-vue-next'
import { useUserStore } from '@/store'
import router from '@/router'
import { loginWithWeChatTicket } from '@/api/login'
const WS_URL = import.meta.env.VITE_WS_URL
const userStore = useUserStore()

let ws = null
//关闭websocket
export const closeWebSocket = () => {
  if (ws) {
    ws.close()
  }
}
//检测支付状态的websocket
export const checkWxPayStatusWebSocket = orderCode => {
  return new Promise((resolve, reject) => {
    ws = new WebSocket(`${WS_URL}/pay?order=${orderCode}`)

    ws.onopen = () => {
      //console.log('连接成功')
    }

    ws.onmessage = e => {
      //console.log(e.data)
      if (e.data === 'success') {
        ws.close()
        resolve({ statusCode: 200, message: '支付成功' })
      } else {
        resolve({ statusCode: 200, message: e.data })
      }
    }

    ws.onclose = () => {
      //console.log('连接关闭')
      reject({ statusCode: 200, message: 'WebSocket连接关闭' })
    }

    ws.onerror = error => {
      //console.error(`连接错误: ${error}`)
      reject({ statusCode: 500, message: `WebSocket连接错误: ${error}` })
    }
  })
}
//检测微信登录状态的websocket
export const checkLoginStatusWebSocket = ticket => {
  //console.log(ticket)
  ws = new WebSocket(WS_URL + `/login?ticket=${ticket}`)
  ws.onopen = () => {}
  ws.onmessage = event => {
    const data = JSON.parse(event.data)
    if (data.code === 200) {
      const params = {
        ticket: ticket
      }
      loginWithWeChatTicket(params).then(res => {
        try {
          //console.log(res + '微信登录成功')
          userStore.login(res.data.token).then(userInfo => {
            if (userInfo) {
              router.path === '/login' ? router.push('/') : router.go(-1)
            }
          })
        } catch (e) {
          MessagePlugin.error('登录失败，请重试!')
        }
      })
    } else {
      MessagePlugin.error(data.error)
    }
  }
  ws.onclose = () => {}
  ws.onerror = error => {
    MessagePlugin.error(error)
  }
}
//检测微信登录状态的websocket
export const checkLoginStatusWebSocket1 = (ticket, callback) => {
  //console.log(ticket)
  ws = new WebSocket(WS_URL + `/login?ticket=${ticket}`)
  ws.onopen = () => {}
  ws.onmessage = event => {
    const data = JSON.parse(event.data)
    // //console.log(event.data.code, 'event.data.code')
    // //console.log(event.data.data, 'event.data.data')
    if (data.code === 200) {
      //微信登录成功
      const params = {
        ticket: ticket
      }
      loginWithWeChatTicket(params).then(res => {
        if (res.code === 200) {
          callback('login_success')
          userStore.login(res.data.token).then(userInfo => {
            if (userInfo) {
              router.push('/')
            }
          })
          closeWebSocket()
          return
        } else {
          MessagePlugin.error('登录失败，请重试!')
          callback('error')
        }
      })
    }
    if (data.code === 201) {
      if (data.msg === 'return_token') {
        callback('login_success')
        userStore.login(data.data).then(userInfo => {
          if (userInfo) {
            router.push('/')
          }
        })
        closeWebSocket()
        return
      }
    }
    if (data.code === 202) {
      callback('success')
    }
    if (data.code === 203) {
      callback('error')
    }
  }
  ws.onclose = () => {}
  ws.onerror = error => {
    MessagePlugin.error(error)
  }
}
